import auto from "@/plugins/auto";
import { defineStore } from "pinia";
import router, { constantRoutes, dynamicRoutes } from "@/router";
import { getRouters } from "@/api/menu";
import Layout from "@/layout/index.vue";
// 匹配views里面所有的.vue文件
const modules = import.meta.glob('./../views/**/*.vue')
const usePermissionStore = defineStore("permission", {
  state: () => {
    return {
      routes: [],
      addRoutes: [],
      defaultRoutes: [],
      sidebarRouters: [],
      indexPage: "", //第一个页面
    };
  },
  actions: {
    setSidebarRouters(routes) {
      this.sidebarRouters = routes;//静态和动态路由
    },
    setDefaultRoutes(routes) {
      this.defaultRoutes = constantRoutes.concat(routes);
    },
    setIndexPages(routes) {
      this.indexPage = routes;
    },
    generateRoutes(roles) {
      //获取路由
      return new Promise((resolve) => {
        getRouters().then((res) => {
          if (
            res.data.length > 0 &&
            res.data[0].children &&
            res.data[0].children.length > 0
          ) {
            res.data[0].children[0].meta.affix = true; //默认第一个固定
          }
          const sdata = JSON.parse(JSON.stringify(res.data));

          const rdata = JSON.parse(JSON.stringify(res.data));
          
          
          const defaultData = JSON.parse(JSON.stringify(res.data));
          let firstPage = ""; //第一个页面
          if (res.data[0].path == "/") {
            firstPage =
              res.data[0].path +
              (res.data[0]?.children[0]?.path
                ? "/" + res.data[0].children[0].path
                : "");
          } else if (res.data[0].children && res.data[0].children.length > 0) {
            firstPage = res.data[0].path + "/" + res.data[0].children[0].path;
          } else {
            firstPage = res.data[0].path;
          }
          firstPage = firstPage.replace("//", "/");
          const sidebarRoutes = filterAsyncRouter(sdata);
          const rewriteRoutes = filterAsyncRouter(rdata, false, true);
          const defaultRoutes = filterAsyncRouter(defaultData);
          const asyncRoutes = filterDynamicRoutes(dynamicRoutes);
          //动态路由查看是否有权限
          asyncRoutes.forEach((route) => {
            router.addRoute(route);
          });
    
          
          this.setSidebarRouters(constantRoutes.concat(sidebarRoutes)); //静态加上通过校验动态路由
          this.setDefaultRoutes(sidebarRoutes);
          this.setIndexPages(firstPage); //设置第一个页面
          
          resolve(rewriteRoutes);//返回路由
        });
      });
    },
  },
});
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter((routes) => {
    if (type && routes.children) {
      routes.children = filterChildren(routes.children);
    }
    if (routes.component) {
      // Layout ParentView 组件特殊处理
      if (routes.component === "Layout") {
        routes.component = Layout; //替换成组件
      } else {
        routes.component = loadView(routes.component); //替换成组件
      }
    }
    if (routes.children != null&&routes.children&& routes.children.length) {
      routes.children = filterAsyncRouter(routes.children, routes , type); //循环调用自己
    } else {
      delete routes["children"]; //删除子路由
      delete routes["redirect"]; //删除重定向
    }
    return true;
  });
}
function filterChildren(childrenMap, lastRouter = false) {
  var children = [];
  childrenMap.forEach((el, index) => {
    if (lastRouter) {
    
      
      el.path = lastRouter.path + "/" + el.path;
      if (el.children && el.children.length) {
        children = children.concat(filterChildren(el.children, el));
        return;
      }
    }
 
    children = children.concat(el);

    
  });

  
  return children;
}
//遍历动态路由是否有权限
function filterDynamicRoutes(routers) {
  const res = [];
  routers.forEach((route) => {
    if (route.permissions) {
         if (auto.hasPermiOr(route.permissions)) {
           res.push(route);//有权限的添加到路由中
         }
      
    } else if (route.roles) {
       if (auto.hasRoleOr(route.roles)) {
         res.push(route);//有权限的添加到路由中
       }
    }
  })
  return res;
}
//处理路由
const loadView = (view) => {
  let res;
  for (const path in modules) {
    const dir = path.split("views/")[1].split(".vue")[0];
    if (dir === view) {
      res = () => modules[path]();
    }
   }
   return res;
};
export default usePermissionStore;
